package uk.ac.lkl.lpp.model.xml;



//import java.lang.reflect.Constructor;
//import java.lang.reflect.InvocationTargetException;

import java.util.Map;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

//import uk.ac.lkl.common.util.Property;
import uk.ac.lkl.lpp.model.PedagogyPlanModel;
import uk.ac.lkl.lpp.ui.BackCompat;
import uk.ac.lkl.lpp.xml.XMLException;


public class ConceptSetProcessor extends ModelElementProcessor {

    public ConceptSetProcessor() {
        super("ConceptSet");
    }


    public void convertDataToElements(PedagogyPlanModel model,
                                      Document document,
                                      Element pedagogyPlanElement) {
        // should be done in base class
        Element parentElement = document.createElement("ConceptSet");
        pedagogyPlanElement.appendChild(parentElement);

        Map<Class, String> conceptMap = model.getConceptMap();

        for (Map.Entry<Class, String> entry : conceptMap.entrySet()) {
            Element childElement = document.createElement("Concept");

            Class cl = entry.getKey();
            String text = entry.getValue();

            String className = cl.getName();

            childElement.setAttribute("class", className);
            childElement.setAttribute("text", text);

            parentElement.appendChild(childElement);
        }
    }


    @Override
    public void convertElementToData(PedagogyPlanModel model,
                                     Element parentElement) throws XMLException {
        try {
            NodeList nodes = parentElement.getElementsByTagName("Concept");
            for (int i = 0; i < nodes.getLength(); i++) {
                Element childElement = (Element) nodes.item(i);
                String className = childElement.getAttribute("class");
                
                // hack to convert pre 0.72 data files
                if (BackCompat.isOldForm(className)) className = BackCompat.upgrade(className);

                String text = childElement.getAttribute("text");

                Class cl = Class.forName(className);
                model.setConcept(cl, text);
            }
        }
        catch (ClassCastException e) {
            throw new XMLException(e);
        }
        catch (ClassNotFoundException e) {
            throw new XMLException(e);
        }
    }

}
